package com.cooper.common.shiro.token;

import com.cooper.base.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Copyright © 2017 com. All rights reserved.
 *
 * @Title: UserUtil.java
 * @Prject: springmvc-mybatis-shiro
 * @Package: com.cooper.common.shiro.token
 * @Description: Session用户工具类
 * @author: JackCooperZ
 * @date: 2017年1月17日 下午6:05:40
 * @version: V1.0
 */
public class UserUtil {

    /**
     * @return
     * @throws
     * @Title: getSession
     * @Description: 获取Session
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * @return
     * @throws
     * @Title: getSubject
     * @Description: 获取当前操作用户
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * @return
     * @throws
     * @Title: getSysUser
     * @Description: 获取当前操作用户实际用户信息
     */
    public static SysUser getSysUser() {
        return (SysUser) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * @return
     * @throws
     * @Title: getUserId
     * @Description: 获取当前操作用户实际用户ID
     */
    public static String getUserId() {
        return getSysUser().getUserId();
    }

    /**
     * @param key
     * @param value
     * @throws
     * @Title: setSessionAttribute
     * @Description: 在session添加属性元素
     */
    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    /**
     * @param key
     * @return
     * @throws
     * @Title: getSessionAttribute
     * @Description: 根据key获取session属性元素
     */
    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    /**
     * @return
     * @throws
     * @Title: isLogin
     * @Description: 判断是否已经登录
     */
    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    /**
     * @throws
     * @Title: logout
     * @Description: 退出登录
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * @param key
     * @return
     * @throws
     * @Title: getKaptcha
     * @Description: 从session中获取验证码值
     */
    public static String getKaptcha(String key) {
        String kaptcha = getSessionAttribute(key).toString();
        return kaptcha;
    }

}
